#!/usr/bin/env python3
import tkinter as tk
from tkinter import messagebox
import json
import os
from datetime import datetime, timedelta

class SalaryDisplayApp:
    def __init__(self, root):
        self.root = root
        self.root.title('每月薪资显示器')
        self.monthly_salary = 0
        self.load_salary()
        self.setup_ui()
        self.update_salary()

    def setup_ui(self):
        # 显示已赚取金额
        self.earned_label = tk.Label(self.root, text='已赚取金额: 0.00 元', font=('Arial', 24))
        self.earned_label.pack(pady=20)

        # 月薪设置输入框
        self.salary_entry = tk.Entry(self.root)
        self.salary_entry.insert(0, str(self.monthly_salary))
        self.salary_entry.pack(pady=5)

        # 设置月薪按钮
        self.set_salary_button = tk.Button(self.root, text='设置月薪', command=self.set_salary)
        self.set_salary_button.pack(pady=10)

    def get_current_month_seconds(self):
        now = datetime.now()
        next_month = now.replace(day=28) + timedelta(days=4)
        last_day = next_month - timedelta(days=next_month.day)
        first_day = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        return (last_day - first_day).total_seconds()

    def get_elapsed_seconds(self):
        now = datetime.now()
        first_day = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        return (now - first_day).total_seconds()

    def update_salary(self):
        if self.monthly_salary > 0:
            month_seconds = self.get_current_month_seconds()
            elapsed_seconds = self.get_elapsed_seconds()
            earned = (self.monthly_salary / month_seconds) * elapsed_seconds
            self.earned_label.config(text=f'已赚取金额: {earned:.2f} 元')
        self.root.after(1000, self.update_salary)

    def set_salary(self):
        try:
            new_salary = float(self.salary_entry.get())
            if new_salary < 0:
                raise ValueError
            self.monthly_salary = new_salary
            self.save_salary()
        except ValueError:
            messagebox.showerror('错误', '请输入有效的正数金额')

    def save_salary(self):
        try:
            with open('salary_config.json', 'w') as f:
                json.dump({'monthly_salary': self.monthly_salary}, f)
        except Exception as e:
            messagebox.showerror('错误', f'保存薪资设置失败: {str(e)}')

    def load_salary(self):
        if os.path.exists('salary_config.json'):
            try:
                with open('salary_config.json', 'r') as f:
                    data = json.load(f)
                    self.monthly_salary = data.get('monthly_salary', 0)
            except Exception as e:
                messagebox.showerror('错误', f'加载薪资设置失败: {str(e)}')

if __name__ == '__main__':
    root = tk.Tk()
    app = SalaryDisplayApp(root)
    root.mainloop()